﻿using System;
using System.ComponentModel;
using System.Windows;
using Microsoft.Practices.Prism.Regions;

namespace CPN.PJN.Silverlight.Common.Helpers.RegionBehaviors
{
    public class ClearViewsRegionBehavior : RegionBehavior
    {
        public const string BehaviorKey = "ClearViews";

        protected override void OnAttach()
        {
            this.Region.PropertyChanged += new PropertyChangedEventHandler(Region_PropertyChanged);
        }

        void Region_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "RegionManager")
            {
                if (this.Region.RegionManager == null)
                {
                    foreach (object view in this.Region.Views)
                    {
                        DependencyObject dependencyObject = view as DependencyObject;
                        if (dependencyObject != null)
                        {
                            dependencyObject.ClearValue(RegionManager.RegionManagerProperty);
                        }

                        if (view is FrameworkElement)
                        {
                            FrameworkElement element = view as FrameworkElement;
                            if (element.DataContext is IDisposable) // DataContext = ViewModel
                            {
                                ((IDisposable)element.DataContext).Dispose();
                            }
                        }
                    }
                }
            }
        }
    }
}
